package com.taxshare.freemark.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @ClassName: FreemarkUtil
 * @Description:
 * @author: luozhongyi
 * @date: 2021/5/11 10:28
 */
@Slf4j
@SuppressWarnings("all")
public class FreemarkUtil {


    /**
     * FreeMark模板配置
     */
    private static final Configuration CONFIGURATION;

    /**
     * 配置模板路径
     */
    private static final String TEMPLATE_PATH = "/template";

    /**
     * 配置模板编码格式
     */
    private static final String ENCODING = "UTF-8";

    static {
        CONFIGURATION = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        CONFIGURATION.setDefaultEncoding(ENCODING);
        CONFIGURATION.setClassForTemplateLoading(com.taxshare.freemark.utils.FreemarkUtil.class,
                TEMPLATE_PATH);
    }

    private FreemarkUtil() {
    }

    /**
     * @param templateName 调用的模板的路径名称
     * @param map          填充的参数
     * @return
     */
    public static String getTemplate(String templateName, Map<String, Object> map) {
        StringWriter out = new StringWriter();
        try {
            Template t = CONFIGURATION.getTemplate(templateName);
            t.process(map, out);
            out.flush();
            return out.getBuffer().toString();
        } catch (Exception e) {
            log.error("FreeMarkUtil文件读取失败{}", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("FreeMarkUtil的out流关闭失败{}", e);
                }
            }
        }
        return null;
    }

    /**
     * @param templateName 调用的模板的路径名称
     * @return
     */
    public static String getTemplateObj(String templateName, Object object) {
        StringWriter out = new StringWriter();
        try {
            Template t = CONFIGURATION.getTemplate(templateName);
            t.process(object, out);
            out.flush();
            return out.getBuffer().toString();
        } catch (Exception e) {
            log.error("FreeMarkUtil文件读取失败{}", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("FreeMarkUtil的out流关闭失败{}", e);
                }
            }
        }
        return null;
    }
}
